﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace Utilities.IO
{
    public class QueueStream : Stream
    {
        public Queue<byte> Buffer { get; protected set; }

        private int readPosition = 0;
        private int writePosition = 0;

        private ManualResetEvent readerMutex;

        public QueueStream()
        {
            Buffer = new Queue<byte>();
            readerMutex = new ManualResetEvent(false);
        }

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }
        public override bool CanWrite
        {
            get
            {
                return true;
            }
        }
        public override bool CanSeek
        {
            get
            { 
                return false;
            }
        }

        public override void Flush()
        {
            throw new NotSupportedException();
        }

        public override long Length
        {
            get
            {
                return Buffer.Count;
            }
        }
        public override long Position
        {
            get
            {
                return 0;
            }
            set
            {
                Seek(value, SeekOrigin.Current);
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (writePosition - readPosition == 0)
                readerMutex.Reset();
            readerMutex.WaitOne();

            count = Math.Min(writePosition - readPosition, count);

            for (int i = 0; i < count; i++)
            {
                buffer[offset + i] = Buffer.Dequeue();
                readPosition ++;
            }

            return count;
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            for (int i = 0; i < count; i++)
            {
                Buffer.Enqueue(buffer[offset + i]);
                writePosition ++;
            }
            readerMutex.Set();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            // Skip bytes
            throw new NotSupportedException();
        }
        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }
    }
}
